package
{
	import flash.desktop.NativeApplication;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.text.Font;
	import flash.ui.Keyboard;
	import flash.utils.Timer;

	public class Main extends Sprite
	{
		public static const GAME_WIDTH:int = 1024;
		public static const GAME_HEIGHT:int = 600;
		
		private var _letterGrid:LetterGrid;
		private var _words:WordList;
		private var _startTime:Date;
		private var _gameOver:GameOverPanel;
		
		
		public function Main()
		{
			init();
			startGame();
			
		}
		
		private function init():void
		{
			var bg:Sprite = new BG();
			addChild(bg);
			
			_letterGrid = new LetterGrid();
			_letterGrid.x = 120;
			_letterGrid.y = 25;
			addChild(_letterGrid);
			
			_words = new WordList(_letterGrid);
			_words.addEventListener(WordList.GAME_OVER_EVENT, onGameOver);
			addChild(_words);
			
			_gameOver = new GameOverPanel();
			_gameOver.x = GAME_WIDTH / 2 - _gameOver.width / 2;
			_gameOver.y = GAME_HEIGHT / 2 - _gameOver.height / 2;
			_gameOver.addEventListener(GameOverPanel.PLAY_AGAIN, startGame);
			
			Font.registerFont(Eraser);
			
			NativeApplication.nativeApplication.addEventListener(Event.DEACTIVATE, onDeactivate, false, 0, true);
			NativeApplication.nativeApplication.addEventListener(KeyboardEvent.KEY_DOWN, handleKeys, false, 0, true);
		}
		
		private function handleKeys(e:KeyboardEvent):void
		{
			if(event.keyCode == Keyboard.BACK)
				NativeApplication.nativeApplication.exit();
		}
		
		private function onDeactivate(e:Event):void
		{
			NativeApplication.nativeApplication.exit();
		}
		
		private function onGameOver(e:Event):void
		{
			var endTime:Date = new Date();
			var secs:int = (endTime.time - _startTime.time) / 1000;
			_gameOver.update(secs);
			addChild(_gameOver);
		}
		
		private function startGame(e:Event=null):void
		{
			if (contains(_gameOver)) removeChild(_gameOver);
			
			_startTime = new Date();
			_words.newGame();
		}
		
	}

}